﻿#include "widget.h"

Widget::Widget(QWidget *parent) :
    BaseEditor(parent)
{
    setupUi(this);

    table=TD_TREND;

    listModel=new QStringListModel(this);
    this->listView->setModel(listModel);

    model=new QSqlTableModel(this);
    this->tableView->setModel(model);

    updateTopic();
    createMenu();
}

void Widget::generateMenu()
{
    menu->addAction(QStringLiteral("新记录... (F1)"),this,&Widget::newItem);
    menu->addSeparator();
    menu->addAction(QStringLiteral("更新类别 (F4)"),this,&Widget::updateTopic);
    menu->addSeparator();
    menu->addAction(QStringLiteral("打开链接 (Alt+W)"),this,&Widget::openUrl);
}

void Widget::keyPressEvent(QKeyEvent *event)
{
    if(event->modifiers() == Qt::AltModifier && event->key() == Qt::Key_W)
        openUrl();
    else
    {
        switch (event->key()) {
        case Qt::Key_F1:
            newItem();
            break;
        case Qt::Key_F4:
            updateTopic();
            break;
        }
    }
}

void Widget::newItem()
{
    AddItem itemAdd;
    if(!selectTopic.isEmpty())
        itemAdd.setTopic(selectTopic);

    if(!selectLabel.isEmpty())
        itemAdd.setLabel(selectLabel);

    itemAdd.move(x() + 100,y() + 50);
    if(itemAdd.exec() == QDialog::Accepted)
        updateView();
}

void Widget::openUrl()
{
    QModelIndex index=this->tableView->currentIndex();
    if(!index.isValid())
        return;

    QString url=index.sibling(index.row(),ADD_COL).data().toString();
    if(!url.isEmpty())
        QDesktopServices::openUrl(QUrl(url));
}

void Widget::updateTopic()
{
    if(this->topics->count() != 0)
        this->topics->clear();

    QStringList items=sp_getTopic(table);
    if(!items.isEmpty())
        this->topics->addItems(items);
}

void Widget::updateView()
{
    if(selectTopic.isEmpty() || selectLabel.isEmpty())
        return;

    model->setTable(table);
    model->setFilter(QString("topic='%1' AND label='%2'")
                     .arg(selectTopic)
                     .arg(selectLabel));
    model->select();

    this->tableView->hideColumn(0);   //id
    this->tableView->hideColumn(1);   //topic
    model->setHeaderData(2,Qt::Horizontal,QStringLiteral("名称"));    //label
    this->tableView->setColumnWidth(2,DEF_WIDTH);
    model->setHeaderData(3,Qt::Horizontal,QStringLiteral("日期"));    //date_
    model->setHeaderData(4,Qt::Horizontal,QStringLiteral("价格"));    //detail
    this->tableView->hideColumn(5);   //addition
}

void Widget::on_topics_currentTextChanged(const QString &text)
{
    selectTopic=text;
    QStringList items=sp_getCategory("label",table,"topic",selectTopic);
    listModel->setStringList(items);
}

void Widget::on_listView_doubleClicked(const QModelIndex &index)
{
    if(selectTopic.isEmpty())
        return;

    if(index.isValid())
    {
        selectLabel=index.data().toString();
        updateView();
    }
}
